﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DAL;
using System.IO;
using Util;

namespace Club.Controllers
{
    public class FacilitiesController : Controller
    {
        ClubEntities mclubModel;
        
        public FacilitiesController()
        {
            mclubModel = new ClubEntities();
        }
        //
        // GET: /Facilities/

        public ActionResult List()
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/Facilities/List/");
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            ViewData.Model = mclubModel.Facilities.ToList();
            return View();
        }
       
        
        //
        // GET: /Facilities/Edit/5
 
        public ActionResult Edit(short id)
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/Facilities/Edit/"+id);
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            var l_edit = mclubModel.Facilities.First(m => m.Id == id);
            return View(l_edit);
        }

        //
        // POST: /Facilities/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
                DAL.User user = (DAL.User)sessionVar["userVar"];
                if (user == null)
                {
                    Response.Redirect("/Default.aspx?prepage=/Facilities/Edit/" + id);
                    return null;
                }
                if (user.RoleId != (short)ROLE_ENUM.ADMIN)
                {
                    Response.Redirect("/AccessDenied.aspx");
                    return null;
                }
                // TODO: Add update logic here
                string l_filename =Util.Common.CommonUtility.GetDateTimeString();
                string l_actualFileName = string.Empty;
                

                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                        string filePath = Path.Combine(HttpContext.Server.MapPath("/img")
                            , l_filename+= Path.GetFileName(file.FileName));
                        l_actualFileName = file.FileName;
                        file.SaveAs(filePath);                       
                    }
                }

                var l_objEdit = mclubModel.Facilities.First(m => m.Id == (short)id);
                if (l_objEdit != null)
                {
                    if(l_actualFileName!=string.Empty)
                        DeleteOldFile(l_objEdit.SystemFileName);
                    l_objEdit.Name = collection["Name"].ToString();
                    l_objEdit.IsUnderMaintenance = collection["IsUnderMaintenance"].Contains("true");
                    l_objEdit.Description = collection["Description"].ToString();
                    l_objEdit.PicUrl =l_actualFileName==string.Empty? l_objEdit.PicUrl:l_actualFileName;
                    l_objEdit.SystemFileName = l_actualFileName == string.Empty ? l_objEdit.SystemFileName : "/img/" + l_filename;
                }
                ViewData["Result"] = "Success";
                mclubModel.SaveChanges();

                return View("Edit",l_objEdit);
            }
            catch
            {
                ViewData["Result"] = "Fail";
                return View();
            }
        }


        public ActionResult New()
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/Facilities/New/");
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            Facility l_objNew = new Facility();
            
            return View(l_objNew);
        }
        [HttpPost]
        public ActionResult New(FormCollection collection)
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/Facilities/New/");
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            Facility l_objNew = new Facility();
            try
            {
                // TODO: Add update logic here
                string l_filename = Util.Common.CommonUtility.GetDateTimeString();
                string l_actualFileName = string.Empty;


                foreach (string inputTagName in Request.Files)
                {
                    HttpPostedFileBase file = Request.Files[inputTagName];
                    if (file.ContentLength > 0)
                    {
                        string filePath = Path.Combine(HttpContext.Server.MapPath("/img")
                            , l_filename += Path.GetFileName(file.FileName));
                        l_actualFileName = file.FileName;
                        file.SaveAs(filePath);
                    }
                }

                
                             
                l_objNew.Name = collection["Name"].ToString();
                l_objNew.IsUnderMaintenance = collection["IsUnderMaintenance"].Contains("true");
                l_objNew.Description = collection["Description"].ToString();
                l_objNew.PicUrl = l_actualFileName == string.Empty ? l_objNew.PicUrl : l_actualFileName;
                l_objNew.SystemFileName = l_actualFileName == string.Empty ? l_objNew.SystemFileName : "/img/" + l_filename;
                mclubModel.AddToFacilities(l_objNew);
                mclubModel.SaveChanges();
                ViewData["Result"] = "Successfully created!";
                return View(l_objNew);
            }
            catch
            {
                ViewData["Result"] = "There's an error creating new facility. Please contact administrator!";
                return View(l_objNew);
            }        
        }
        private void DeleteOldFile(string aFileName)
        {
            FileInfo l_finfo = new FileInfo(HttpContext.Server.MapPath("/") + aFileName);
            if (l_finfo.Exists)
            {
                l_finfo.Delete();
            }
        }

        
        public ActionResult Delete(int? id)
        {
            Dictionary<string, object> sessionVar = (Dictionary<string, object>)Session["vars"];
            DAL.User user = (DAL.User)sessionVar["userVar"];
            if (user == null)
            {
                Response.Redirect("/Default.aspx?prepage=/Facilities/Delete/" + id);
                return null;
            }
            if (user.RoleId != (short)ROLE_ENUM.ADMIN)
            {
                Response.Redirect("/AccessDenied.aspx");
                return null;
            }
            //Facility l_objNew = new Facility();
            try
            {
                // TODO: Add update logic here                
                var deleteobj = mclubModel.Facilities.First(m => m.Id == id);
                if (deleteobj != null)
                {
                    mclubModel.DeleteObject(deleteobj);
                    mclubModel.SaveChanges();
                    ViewData["Result"] = "Successfully deleted!";
                    ViewData.Model = mclubModel.Facilities.ToList();
                    return View("List");
                }
                ViewData.Model = mclubModel.Facilities.ToList();
                return View("List");
            }
            catch
            {
                ViewData["Result"] = "There's an error deleting facility. Please contact administrator!";
                ViewData.Model = mclubModel.Facilities.ToList();
                return View("List");
            }   
        }
    }
}
